/**
 * 主页JS
 */
let scsCurrentPage = 1, scsPageSize = 15, serviceSelectType = '', serviceSelectDistinct = '', scsLng = 0, scsLat = 0,
	//searchSize:搜索历史记录最大的条数
	searchSize = 8,serviceOrderTotalPage = 0;
$(function() {
	//获取当前城市名
	let geolocation;
	//加载地图，调用浏览器定位服务
	let map = new AMap.Map('aMapDiv', {
	    resizeEnable: true
	});
    $('.close-login').click(function() {
		$('#middleMain,.page-mask').hide();
		$('.btn-grab-order,.btn-disabled').text('我要抢单');
		$('.btn-disabled').removeClass('btn-disabled').addClass('btn-grab-order');
	});
	//搜索框获得焦点
	$('#searchServiceTitle').focus(function () {
		let searchHistoryArray = localStorage.getItem('searchHistory');
		if (isNull(searchHistoryArray) || searchHistoryArray.length < 1) {
			return;
		}
        setSearchHistoryPosition();
        searchHistoryArray = JSON.parse(searchHistoryArray);
        $('.search-history ul li').remove();
        for (let i = 0; i < searchHistoryArray.length; i++) {
            if (!isNull(searchHistoryArray[i])) {
                $('.search-history ul').append('<li>' + searchHistoryArray[i] + '</li>');
            }
        }
        $('.search-history').show();
	});
	$(".search-history").on("click", "li", function () {
		$('#searchServiceTitle').val($(this).text());
		searchOrderByTitle();
	});
	//搜索框失去焦点
	$(document).click(function () {
		//如果点击的不是searchServiceTitle搜索框，则隐藏
		if (this.activeElement.id != $('#searchServiceTitle')[0].id) {
			$('.search-history').hide();
		}
	});
	//实例化城市查询类
	let citySearch = new AMap.CitySearch(), lsName = localStorage.getItem(LAST_CITY_NAME_KEY),
		lsCode = localStorage.getItem(LAST_CITY_ID_KEY);
	//如果是从城市选择页面并且选择了切换城市返回时设置当前城市信息
	if (!isNull(lsCode) && !isNull(lsName)) {
		setCurrentCity();
		initPageInfo();//请求主页页面数据
	} else {
		//根据ID定位城市
		citySearch.getLocalCity(function (status, result) {
			if (status === 'complete' && result.info === 'OK') {
                citySearchCompleteByIP(result);
			} else {
				setCurrentCity();
			}
			initPageInfo();//请求主页页面数据
		});
	}

	$('.search-button').click(function() {
		//将搜索历史记录存入localStorage中
		let searchHistoryStr = localStorage.getItem('searchHistory'), titleValue = $('#searchServiceTitle').val();
		if (isNull(titleValue)) {
            searchOrderByTitle();
            return;
		}
		let searchStorageArray = isNull(searchHistoryStr) ? [] : JSON.parse(searchHistoryStr);
		//如果搜索历史中不存在，则添加到历史记录中，否则不添加
		if (searchStorageArray.indexOf(titleValue) < 0) {
			searchStorageArray.unshift(titleValue);
		}
		let searchLen = searchStorageArray.length;
		//如果searchStorageArray中的元素个数超过searchSize，则删除最后1个元素
		if (searchLen > searchSize){
			searchStorageArray.splice(searchLen - 1,1);
		}
		searchOrderByTitle();
        localStorage.setItem('searchHistory', JSON.stringify(searchStorageArray));
	});
	//浏览器定位
    map.plugin('AMap.Geolocation', function() {
        geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,//是否使用高精度定位，默认:true
            timeout: 20000,          //超过20秒后停止定位，默认：无穷大
            buttonOffset: new AMap.Pixel(10,30),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
            zoomToAccuracy: true,      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
            buttonPosition:'RB'
        });
        //map.addControl(geolocation);
        geolocation.getCurrentPosition();
		//返回定位信息
		AMap.event.addListener(geolocation, 'complete', onComplete);
		//返回定位出错信息
		AMap.event.addListener(geolocation, 'error', onError);
    });
});
//定位失败的情况下，设置当前城市信息
function setCurrentCity(){
	last_city_name = localStorage.getItem(LAST_CITY_NAME_KEY);
	//如果上次保存的城市信息不存在，就将默认的城市信息赋值给当前城市
	if (!isNull(last_city_name)) {
		currentCityCode = localStorage.getItem(LAST_CITY_ID_KEY);
		currentCityName = localStorage.getItem(LAST_CITY_NAME_KEY);
	}else {
        currentCityCode = defaultCityCode;
        currentCityName = defaultCityName;
	}
    let lastCityObj = getLastCity();
    if (lastCityObj == null || currentCityCode != lastCityObj.code) {
        lastCityObj = {'code': currentCityCode, 'name': currentCityName};
        localStorage.setItem(LAST_CITY, JSON.stringify(lastCityObj));
    }
}
//初始化主页页面数据，如：服务类型、区域等
function initPageInfo() {
	//初始化页面信息
	let sTypeParentId = '1', serviceTypeArr = getDictionaries(1),
		areaStr = localStorage.getItem(ALL_AREA_KEY + '_' + currentCityCode),
		myCityCode = currentCityCode, myCityName = currentCityName, myCity = $('#myCity');
	if (!isNull(serviceTypeArr)) {
		appendServiceType(serviceTypeArr);
		//服务类型监听
		addTypeClick();
		sTypeParentId = '';
	}
	if (!isNull(areaStr)) {
		appendArea(JSON.parse(areaStr));
		//区域监听
		addAreaClick();
		if (!isNull(serviceTypeArr)) {
			myCity.html(currentCityName);
			myCity.attr('name', currentCityCode);
			loadIndexData();
			return;
		}
		myCityName = '';
		myCityCode = '';
	}
	$.ajax({
		type: 'post',
		url: 'index/initPageInfo',
		dataType: 'json',
		async: false,
		timeout: 30000,
		data: {cityCode: myCityCode, cityName: myCityName, parentId: sTypeParentId},
		success: function(result) {
			if (result.status != '0') {
				return;
			}
			localStorage.setItem(LAST_CITY_ID_KEY, result.cityCode);
			localStorage.setItem(LAST_CITY_NAME_KEY, currentCityName);
			myCity.html(currentCityName);
			if (isNull(currentCityCode) || currentCityCode.toLowerCase() == 'null') {
				currentCityCode = result.cityCode;
			}
			myCity.attr('name', currentCityCode);
			localStorage.setItem(LAST_CITY_ID_KEY, currentCityCode);
			//添加区县
			appendArea(result.areaList);
			//添加服务类型
			appendServiceType(result.serviceTypeList);
			//服务类型监听
			addTypeClick();
			//区域监听
			addAreaClick();
		}
	});
	loadIndexData();
}

function loadIndexData() {
	scsCurrentPage = 1;
	queryIndexServiceOrderData(scsCurrentPage, scsPageSize);
}

/**
 * 添加区县
 * @param areaArray 区县数组
 */
function appendArea(areaArray) {
	if (areaArray == null) {
		return;
	}
	let areaHtmlArr = [];
	//添加服务区域信息
	for (let i = 0; i < areaArray.length; i++) {
	    let areaObj = areaArray[i];
        areaHtmlArr.push('<a id="' + areaObj.areaCode + '">' + areaObj.areaName + '</a>');
	}
    $('#serviceDistance').append(areaHtmlArr.join(''));
	localStorage.setItem(ALL_AREA_KEY + '_' + currentCityCode, JSON.stringify(areaArray));
}

/**
 * 添加服务类型
 * @param stArray 服务类型数组
 */
function appendServiceType(stArray) {
	if (stArray == null) {
		return;
	}
	let serviceTypeArr = [];
	for (let j = 0; j < stArray.length; j++) {
		let st = stArray[j];
		serviceTypeArr.push('<a id="' + st.id + '">' + st.dicName + '</a>');
	}
	$('#serviceType').append(serviceTypeArr.join(''));
}
/**
 * 添加类型点击事件
 */
function addTypeClick() {
	let ssta = $('.service-select-type a');
	ssta.click(function () {
	    //上次选择的服务类型ID
        let lastTypeId = $('.service-select-type .default-type')[0].id,
		selectedTypeId = this.id;
		serviceSelectType = selectedTypeId == '0' ? '' : selectedTypeId;
		ssta.removeClass('default-type').each(function () {
			if (selectedTypeId == this.id) {
				$(this).addClass('default-type');
			}
		});
		//如果上次点击的服务类型跟本次点击的服务类型不一样，才重新加载数据
		if (lastTypeId != selectedTypeId) {
            queryIndexServiceOrderData(scsCurrentPage, scsPageSize);
        }
	});
}

/**
 * 添加区县点击事件
 */
function addAreaClick() {
	let ssda = $('.service-select-distinct a');
	ssda.click(function () {
	    //上次点击的区域ID
		let lastAreaId = $('.service-distance .default-type')[0].id,
            selectedAreaId = this.id;
		serviceSelectDistinct = selectedAreaId == '0' ? '' : selectedAreaId;
		ssda.removeClass('default-type').each(function () {
			if (selectedAreaId == this.id) {
				$(this).addClass('default-type');
			}
		});
		//如果上次点击的区域ID不等于本次点击的区域ID，则重新加载
		if (lastAreaId != selectedAreaId){
            queryIndexServiceOrderData(scsCurrentPage, scsPageSize);
        }
	});
}
/**
 * 加载主页数据
 * @param currentPage  当前面码
 * @param pageSize   每页显示记录数
 */
function queryIndexServiceOrderData(currentPage, pageSize) {
	$('.page-mask,.loading').show();
	$.ajax({
		type: 'post',
		url: 'index/queryServiceOrder',
		dataType: 'json',
		//async: false,//为false时，page-mask和loading都不显示
		timeout: 30000,
		data: {
			cityCode: currentCityCode,
			cityName: currentCityName,
			currentPage: currentPage,
			pageSize: pageSize,
			soAreaCode: serviceSelectDistinct,
			serviceTypeId: serviceSelectType,
			soName: $('#searchServiceTitle').val()
		},
		success: function(pageOrder) {
            loadOrderList(currentPage, pageSize, pageOrder);
		},
		error: function () {
			hideMaskLoading();
			alert('系统太忙了，请稍候再试！')
		}
	});
}

/**
 * 加载订单列表
 * @param currentPage 当前页号
 * @param pageSize 每页显示的订单数
 * @param pageOrder 订单分页数据
 */
function loadOrderList(currentPage, pageSize,pageOrder) {
    let serviceOrderArray = pageOrder.list,serviceList = $('#serviceList'),paginate = $('.wp-paginate');
    serviceList.children().remove();
    if (serviceOrderArray != null && serviceOrderArray.length > 0) {
        //服务订单数据
        let appendArr = [];
        for (let s = 0; s < serviceOrderArray.length; s ++) {
            let order = serviceOrderArray[s], phone = order.soPhone;
            let yourDistance = '天涯海角', soBillNumber = order.soBillNumber;
            appendArr.push(getOrderHtml(s,soBillNumber,order,phone,yourDistance));
        }
        serviceList.append(appendArr.join('')).show();
		textOrderInfo(serviceOrderArray);
        //添加分页工具栏
        paginate.children().remove();
        //总记录数,总页数
        serviceOrderTotalPage = parseInt(pageOrder.pages);

        let ellipsisLi = '<li style="width: 14px;color: #b42323;font-weight: 800;">…</li>',
            pageNums = pageOrder.navigatepageNums, aHref = 'href="javascript:void(0)"';
        let firstClass = 'first-page', previousClass = 'previous-page', isHave = '';
        //如果没有上一页
        if (!pageOrder.hasPreviousPage) {
            firstClass = 'no-first';
            previousClass = 'no-previous';
            isHave = 'no-have';
        }
        let appendStr = '<li title="第一页" class="' + firstClass + '"><a ' + aHref + ' class="first ' + isHave + '"></a></li>' +
            '<li title="上一页" class="' + previousClass + '"><a ' + aHref + ' class="previous ' + isHave + '"></a></li>';
        if (pageNums[0] > 1){
            appendStr += ellipsisLi;
        }
        if (serviceOrderTotalPage > 0) {
            //页面要显示的页数集合
            let pagingNumber = pageOrder.navigatepageNums;
            for (let g = 0; g < pagingNumber.length; g++) {
                let currentClass = pagingNumber[g] == currentPage ? 'current' : 'have';
                appendStr += '<li><a ' + aHref + ' class="page ' + currentClass + '">' + pagingNumber[g] + '</a></li>';
            }
        }
        if (pageNums[pageNums.length - 1] < pageOrder.pages){
            appendStr += ellipsisLi;
        }
        let nextClass = 'next-page', lastClass = 'last-page';
        isHave = '';
        //如果没有下一页
        if (!pageOrder.hasNextPage){
            nextClass = 'no-next';
            lastClass = 'no-last';
            isHave = 'no-have';
        }
        appendStr += '<li title="下一页" class="' + nextClass + '"><a ' + aHref + ' class="next ' + isHave + '"></a></li>' +
            '<li title="最后一页" class="' + lastClass + '"><a ' + aHref + ' class="last ' + isHave + '"></a></li>';
        paginate.append(appendStr);
    } else {
        serviceList.append('<span style="fonts-size: 18px;">当前城市没有服务订单，要不换个城市试试？</span>');
    }
    let leftCss = 'border-left-color', rightCss = 'border-right-color';
    $(".first-page").mouseover(function () {
        $(this).css(leftCss, "#ffa12d");
    }).mouseout(function () {
        $(this).css(leftCss, '#b42323');
    });
    $(".last-page").hover(function () {
        $(this).css(rightCss, "#ffa12d");
    }).mouseout(function () {
        $(this).css(rightCss, '#b42323');
    });
    //分页数字点击事件
    $(".wp-paginate a").click(function() {
        let className = this.className;
        //如果class不包含no-have，并且不是当前页
        if (className.indexOf('no-have') == -1 && parseInt(this.innerText) != currentPage) {
            if (className.indexOf('first') > -1) {
                currentPage = 1;
            } else if (className.indexOf('previous') > -1) {
                currentPage = currentPage > 1 ? currentPage - 1 : 1;
            } else if (className.indexOf('next') > -1) {
                currentPage = currentPage < serviceOrderTotalPage ? currentPage + 1 : serviceOrderTotalPage;
            } else if (className.indexOf('last') > -1) {
                currentPage = serviceOrderTotalPage;
            } else {
                currentPage = parseInt(this.innerText);
            }
            queryIndexServiceOrderData(currentPage, pageSize);
        }
    });
    //重新设置页脚的位置
    setIndexFooterPosition();
    //隐藏加载图片
    hideMaskLoading();
    //统计订单中的“离我的”距离
    countYourDistance();
}
/**
 * 隐藏遮罩层和加载图片
 */
function hideMaskLoading() {
	$('.page-mask,.loading').hide();
}
/**
 * 设置主页上的footer位置
 */
function setIndexFooterPosition(){
	let footer = $('#footer');
	let headerHeight = $('header').height(), typeDistanceHeight = $('.service-type-distance').height(),
		searchHeight = $('.search-fieldset').height(), serviceListHeight = $('#serviceList').height(),
		footerHeight = footer.height();
	let footerBottom = $(window).height() - headerHeight - typeDistanceHeight - searchHeight - serviceListHeight - footerHeight;
	if (footerBottom > 80) {
		footer.css({'bottom':'0','position':'fixed'});
	}else {
		footer.css('position','static');
	}
}
//解析定位结果
function onComplete(data) {
	scsLng = data.position.getLng();
	scsLat = data.position.getLat();
	localStorage.setItem(LAST_LNG, scsLng);//经度
	localStorage.setItem(LAST_LAT, scsLat);//纬度
	sessionStorage.setItem(LAST_LNG, scsLng);
	sessionStorage.setItem(LAST_LAT, scsLat);
	countYourDistance();
}

/**
 * 重新计算用户当前位置(高德地图基于浏览器定位)与订单服务地址的距离
 */
function countYourDistance() {
	if (scsLat < 1 || scsLng < 1) {
		return;
	}
	$(".order-lnglat").each(function () {
		let lnglatArray = this.value.split('_');
		let yourDistance = getDistanceByLatLng(scsLng, scsLat, Number(lnglatArray[1]), Number(lnglatArray[0]));
		let billNoId = this.id.split('_')[1], disStr = (yourDistance / 1000).toFixed(2);
		$('#distance_' + this.id.split('_')[1]).text(disStr + ' Km');
		let aObj = I('a_' + billNoId);
		aObj.href += '&distance=' + disStr + 'Km';
	});
}
//解析定位错误信息
function onError(e) {
	getLat();
	getLng();
	countYourDistance();
}
function getLat() {
	if (isNull(scsLat) || scsLat < 0) {
		//从sessionStorage和localStorage中获取经纬度信息
		scsLat = sessionStorage.getItem(LAST_LAT);
		if (isNull(scsLat) || scsLat <= 0) {
            scsLat = localStorage.getItem(LAST_LAT);
        }
	}
	if (!isNull(scsLat)) {
		scsLat = Number(scsLat);
	}
	return scsLat;
}
function getLng() {
	if (isNull(scsLng) && scsLng <= 0) {
		//从sessionStorage和localStorage中获取经纬度信息
		scsLng = sessionStorage.getItem(LAST_LNG);
		if (isNull(scsLng) || scsLng <= 0) {
			scsLng = localStorage.getItem(LAST_LNG);
		}
	}
	if (!isNull(scsLng)) {
		scsLng = Number(scsLng);
	}
	return scsLng;
}

/**
 * 设置历史搜索框位置
 */
function setSearchHistoryPosition() {
	let searchHistoryRight = ($(document).width() - $('#serviceList').width()) / 2 + $('.search-button').width() + 12;
	$('.search-history').css('right', searchHistoryRight + 'px');
}
/**
 * 通过标题查询订单
 */
function searchOrderByTitle() {
	scsCurrentPage = 1;
	queryIndexServiceOrderData(scsCurrentPage, scsPageSize);
}
/**
 * 根据IP定位城市成功的后续处理
 * @param result
 */
function citySearchCompleteByIP(result) {
    if (!(result && result.city && result.bounds)) {
        return;
    }
    currentCityName = result.city;
    let nameLen = currentCityName.length;
    let delShiName = currentCityName.substr( nameLen- 1,nameLen);
    if (delShiName == '市'){
		currentCityName = currentCityName.substr( 0,nameLen - 1);
    }
    //将上一次的城市名跟当前城市名相比较获取城市编号
    last_city_name = localStorage.getItem(LAST_CITY_NAME_KEY);
    if (last_city_name == currentCityName || (currentCityName + '市') == last_city_name) {
        currentCityCode = localStorage.getItem(LAST_CITY_ID_KEY);
    } else {
        currentCityCode = '';
        localStorage.setItem(LAST_CITY_ID_KEY, '');
        localStorage.setItem(LAST_CITY_NAME_KEY, currentCityName);
    }
}

/**
 * 给订单的标题、地址等易被植入恶意代码的字段信息使用text方法赋值，以应对这种攻击行为
 * @param serviceOrderArray 订单数组
 */
function textOrderInfo(serviceOrderArray) {
	for (let s = 0; s < serviceOrderArray.length; s ++) {
		let soObj = serviceOrderArray[s];
		let orderAddress = soObj.soAddress, areaName = soObj.areaName, billNo = soObj.soBillNumber,
			province = soObj.provinceName, city = soObj.cityName;
		if (province != city) {
			city = province + city;
		}
		if (province != city) {
			city = province + city;
		}
		//如果区/县不为空且地址里不包含区/县名
		if (!isNull(areaName) && orderAddress.indexOf(areaName) < 0){
			orderAddress = areaName + orderAddress;
		}
		//如果地址里不包含城市名
		if (!isNull(city) && orderAddress.indexOf(city) < 0){
			orderAddress = city + orderAddress;
		}
		$('#a_' + billNo).text(soObj.soName);
		$('#desc_' + billNo).text('地址：' + orderAddress);
	}
}
/**
 * 获取订单html
 * 注：此处标题和地址等用户输入的内容，不直接在这里拼接，防止用户的JS脚本等xss的恶意代码攻击行为；
 * 改用JS的text方法（不用html('<script>alert("xss")</script>')或innerHTML方法，
 * 因为会直接执行用户的恶意代码，攻击网站），因为该方法不会执行恶意代码，而是直接将恶意代码当作普通文本输出到页面。
 * @returns {string}
 */
function getOrderHtml(s,soBillNumber,order,phone,yourDistance) {
	return '<div id="serviceInfo' + s + '" class="service-info">' +
	'<input type="hidden" id="issuerUserId_' + soBillNumber + '" value="' + order.soUserId+'"/>' +
	'<input type="hidden" id="order_' + soBillNumber + '" class="order-lnglat" value="'+order.soLat + '_' + order.soLng +'"/>' +
	'<div>' +
	'<strong class="service-title">' +
	'<a id="a_' + soBillNumber + '" target="_blank" href="/userPages/orderDetail.html?oid=' + soBillNumber + '"></a>' +
	'</strong>' +
	'<div class="so-top">' +
	'<div class="one">发布：' + order.soOrderDate + '</div>' +
	'<div class="two">类型：' + order.serviceTypeName + '</div>' +
	'<div style="line-height:21px;">金额：<strong style="color: #b42323;">' + order.soAmount + '</strong>&nbsp;元</div>' +
	'</div>' +
	'<div class="so-down">' +
	'<div class="one">服务：' + order.soServiceDate + '</div>' +
	'<div class="two">距您：<lable id="distance_' + soBillNumber + '">' + yourDistance + '</lable></div>' +
	'<div>电话：' + phone + '</div>' +
	'</div>' +
	'<div id="desc_' + soBillNumber + '" class="so-down"></div>' +
	'</div>' +
	'<span class="grab-order">' +
	'<button id="btnGrabOrder' + s + '" onclick="robServiceOrder(\''+soBillNumber+'\',' + s + ')" class="btn-grab-order">我要抢单</button>' +
	'</span>' +
	'</div>';
}

/**
 * 获取上次的城市对象
 */
function getLastCity() {
    let lc = localStorage.getItem(LAST_CITY);
    return isNull(lc) ? '' : JSON.parse(lc);
}